using LazyFieldDemo.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;

namespace LazyFieldDemo.Handlers {
    public class CustomerPartHandler : ContentHandler {
        private readonly IContentManager _contentManager;

        public CustomerPartHandler(IRepository<CustomerPartRecord> repository, IContentManager contentManager) {
            _contentManager = contentManager;
            Filters.Add(StorageFilter.For(repository));
            OnActivated<CustomerPart>(LazyLoadHandlers);
        }

        private void LazyLoadHandlers(ActivatedContentContext context, CustomerPart part) {
            part.ShippingAddressField.Loader(address => {
                var addressContentItem = part.Record.ShippingAddressId != null ? _contentManager.Get<AddressPart>(part.Record.ShippingAddressId.Value) : default(AddressPart);
                if(addressContentItem == null) {
                    addressContentItem = _contentManager.Create<AddressPart>("Address", VersionOptions.Published);
                    part.Record.ShippingAddressId = addressContentItem.Id;
                }
                return addressContentItem;
            });

            part.ShippingAddressField.Setter(address => {
                part.Record.ShippingAddressId = address != null ? address.Id : default(int?);
                return address;
            });

            part.BillingAddressField.Loader(address => {
                var addressContentItem = part.Record.BillingAddressId != null ? _contentManager.Get<AddressPart>(part.Record.BillingAddressId.Value) : default(AddressPart);
                if (addressContentItem == null) {
                    addressContentItem = _contentManager.Create<AddressPart>("Address", VersionOptions.Published);
                    part.Record.BillingAddressId = addressContentItem.Id;
                }
                return addressContentItem;
            });

            part.BillingAddressField.Setter(address => {
                part.Record.BillingAddressId = address != null ? address.Id : default(int?);
                return address;
            });
        }
    }
}